package org.example.test.consumer;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.message.MessageExt;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author zhangjg
 * @desc
 * @date 2023/05/12 16:59
 **/
@Slf4j
public class TC {

    public static void main(String[] args) {
        String nameSrv = args[0];
        String topicName = args[1];
        AtomicLong consumeTimes = new AtomicLong(0);
        // 初始化consumer，并设置consumer group name
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("cg_order");
        // 设置NameServer地址
        consumer.setNamesrvAddr(nameSrv);
        //订阅一个或多个topic，并指定tag过滤条件，这里指定*表示接收所有tag的消息
        try {
            consumer.subscribe(topicName, "*");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        //注册回调接口来处理从Broker中收到的消息
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                for (MessageExt msg : msgs) {
                    log.info(new String(msg.getBody(), StandardCharsets.UTF_8));
                    consumeTimes.incrementAndGet();
                }
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        // 启动Consumer
        try {
            consumer.start();
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        log.info("消费者 Started. 消费总条数={}",consumeTimes.get());

    }
}
